package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("下单成功");
    }

//    @GetMapping("/userPage")
//    public R<Page<Orders>> page(int page,int pageSize){
//        Page<Orders> pageInfo = new Page<>(page, pageSize);
//        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
//        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
//        lqw.orderByDesc(Orders::getOrderTime);
//        orderService.page(pageInfo);
//        return R.success(pageInfo);
//    }

    /**
     * 历史订单展示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")//返回的数据中有订单数据还有订单明细数据
    public R<Page<OrderDto>> page(int page,int pageSize){

        Page<Orders> ordersPage=new Page<>(page,pageSize);
        Page<OrderDto> orderDtoPage=new Page<>(page,pageSize);

//        查询Orders表中的订单数据
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,BaseContext.getCurrentId());
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage,lqw);

//        对OrderDto的订单属性进行赋值
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrderDto> orderDtoList=ordersList.stream().map(((item)->{
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item,orderDto);
            //        查询订单明细数据
            Long orderId = item.getId();//获取订单id
            LambdaQueryWrapper<OrderDetail> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> list = orderDetailService.list(lqw2);
            orderDto.setOrderDetails(list);
            return orderDto;
        })).collect(Collectors.toList());

//        第一次复制是复制分页中的records信息并添加订单明细信息，第二次复制是复制分页的所有信息
//        除了records，因为records信息需要重新设置
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");
        orderDtoPage.setRecords(orderDtoList);
        return R.success(orderDtoPage);
    }

    @PostMapping("/again")
    public R<String> again(@RequestBody Map<String,String> map){
        String ids = map.get("id");

        long id = Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> lqw=new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,id);

//        获取该订单对应的所有的订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.list(lqw);

//        通过用户id把原来的购物车给清空，这里的clean方法是视频中讲过的,建议将该方法抽取到service中，那么这里就可以直接调用了
        shoppingCartService.clean();

        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList=orderDetailList.stream().map(((item)->{
//            把order表中的OrderDetails表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId!=null){
//                如果是菜品添加到菜品的查询条件
                shoppingCart.setDishId(dishId);
            }
            else{
//                添加购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        })).collect(Collectors.toList());

//        把携带数据的购物车批量插入购物车表，这个批量保存的方法要使用熟练
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }

    /**
     * 后端分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getPage(int page,int pageSize,String number,String beginTime,String endTime){
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.like(number!=null,Orders::getNumber,number)
                        .gt(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime)
                                .lt(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,lqw);

//        List<Orders> records = pageInfo.getRecords();
//        records = records.stream().map((item) -> {
//
//            item.setUserName("用户" + item.getUserId());
//
//            return item;
//        }).collect(Collectors.toList());

        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> send(@RequestBody Orders orders){
        Long id = orders.getId();
        Orders order = orderService.getById(id);
        order.setStatus(orders.getStatus());
        orderService.updateById(order);
        return R.success("订单状态修改成功");
    }
}
